package com.hj.system.system.config;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class SocketClient {
    public static String sendMessage(String ip, int port, String message) {
        Socket socket = null;
        OutputStream socketOut = null;
        try {
            try {
                socket = new Socket(ip, port);
            } catch (Exception e) {
                e.printStackTrace();
                return "服务器未响应";
            }
            // 发送 out
            socketOut = socket.getOutputStream();
            socketOut.write(message.getBytes());
            //reader = socket.getInputStream();//// 接收服务器的反馈
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String s = null;
            while ((s = reader.readLine()) != null) {
                sb.append(s);
            }
            reader.close();
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "服务器未响应";
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
                if (socketOut != null) {
                    socketOut.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
